package com.px.auth.security;

import com.px.auth.mapper.UserMapper;
import com.px.auth.model.UserModel;
import com.px.common.core.RespCode;
import com.px.common.core.RespException;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class VUserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(@NonNull String username) throws UsernameNotFoundException {
        UserModel userModel = userMapper.getByUsername(username);
        if (userModel == null)
            throw new UsernameNotFoundException(username);
        if (userModel.getIp() != null)
            throw new RespException(RespCode.IP_INVALID, "禁止使用IP地址: " + userModel.getIp());
        boolean enabled = !(userModel.getDisabled() != null && userModel.getDisabled() == 1);
        String roles = "";
        if (userModel.getRoles() != null)
            roles = userModel.json2roles(userModel.getRoles());
        return new User(
                String.valueOf(userModel.getId()),
                userModel.getPassword(),
                enabled,
                true,
                true,
                true,
                AuthorityUtils.commaSeparatedStringToAuthorityList(roles));
    }
}
